package cn.lena.weblog.controller;

import cn.lena.weblog.domain.User;
import cn.lena.weblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class LoginController {

	@Autowired
	private UserService userService;

	@GetMapping({"","/"})
	public String loginPage(HttpSession session){
		if (session.getAttribute("user") == null) {
			return "user/login";    //用户没有登录，或者登录已经失效
		}
		return "user/personal";
	}

	/*为了方便测试，使用以下代码*/
	/*------------------------------------------------------------*/

/*	@Autowired
	private PassageService passageService;

	@Autowired
	private CatagoryService catagoryService;

	@GetMapping({"","/"})
	public String loginPage(HttpSession session, Model model){
		User user = userService.findByUserId(1001);
		session.setAttribute("user",user);
		return "user/personal";
	}*/

	/*------------------------------------------------------------*/

	@PostMapping("change")//t
	String change(@RequestParam String password,@RequestParam String newPass,
				  Model model,HttpSession session){
		User user=(User)session.getAttribute("user");
		System.out.println(user);
		int i = userService.findPassword(user.getUserId(), password);
		if(i!=1){
			model.addAttribute("errorMessage","原先密码输入不正确");
			return "user/personal-changePass";
		}else{
			i=userService.changePassage(user.getUserId(),newPass);
			if(i==1){
				model.addAttribute("errorMessage","修改成功");
				return "user/personal-changePass";
			}
		}
		model.addAttribute("errorMessage","修改失败");
		return "user/personal-changePass";
	}

	@PostMapping("login")//t
	//获取页面表单中name为userId和password的输入框值
	String login(@RequestParam Integer userId, @RequestParam String password,
				 Model model, HttpSession session,RedirectAttributes attributes){
		//System.out.println(userId);
		//System.out.println(password);
		User user = userService.login(userId, password);
		if (user==null){
			System.out.println("error");
			attributes.addFlashAttribute("LoginMsg","账号或密码输入错误");
			return "redirect:/user";
		}
		session.setAttribute("user",user);
		return "user/personal";
	}

	@GetMapping("/logout")
	String logout(HttpSession session){
		session.removeAttribute("user");
		return "redirect:/user";		//用户界面：及登陆页面
	}
}
